import axios from "axios";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { ListType } from "../home";
import { NavBar, Swiper } from "react-vant";
import { GoodInfo } from "../../components";
import { CartO, ChatO, ShopO } from "@react-vant/icons";
import { ActionBar } from "react-vant";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../store";

const Index: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [v, setV] = useState<ListType>({} as ListType);
  // 1. 获取id
  const { id } = useParams();
  // 2. 通过id 查找 数据
  const fetchData = async () => {
    const resp = await axios.get("/api/list/" + id);
    console.log(resp.data);
    setV(resp.data.data);
  };
  // 3. 副作用
  useEffect(() => {
    fetchData();
  }, []);
  // 4. 获取仓库数据
  const carList = useSelector((state: RootState) => state.car.carList);
  const totalCount = carList.reduce((p, n) => p + n.count, 0)
  if (!v.id) {
    return <div>数据加载中...</div>;
  }

  return (
    <div>
      <NavBar onClickLeft={() => navigate(-1)} title={v.title}></NavBar>
      <Swiper>
        {v.images.map((v, i) => {
          return (
            <Swiper.Item key={i}>
              <img src={v} alt="" style={{ width: "100%", height: 200 }} />
            </Swiper.Item>
          );
        })}
      </Swiper>
      <GoodInfo
        title={v.title}
        price={v.price}
        word={v.word}
        height={100}
      ></GoodInfo>

      <ActionBar>
        <ActionBar.Icon icon={<ChatO />} text="客服" />
        <ActionBar.Icon icon={<CartO />} badge={{ content: totalCount }} text="购物车" onClick={() => navigate('/car')}/>
        <ActionBar.Icon icon={<ShopO />} text="店铺" />
        <ActionBar.Button
          type="warning"
          text="加入购物车"
          onClick={() =>
            dispatch({
              type: "addCarList",
              payload: { ...v, count: 1, state: false },
            })
          }
        />
        <ActionBar.Button
          type="danger"
          text="立即购买"
          onClick={() => navigate(`/order/${v.price}/${v.title}`)}
        />
      </ActionBar>
    </div>
  );
};

export default Index;
